<?php

namespace addons\shopro\listener\order;

use addons\shopro\exception\Exception;
use addons\shopro\model\OrderItem;
use addons\shopro\model\Config;
use addons\shopro\model\Order;

/**
 * 订单确认收货
 */
class Confirm
{
    // 订单确认收货后
    public function orderConfirmAfter(&$params)
    {
        $order = $params['order'];

        $order = Order::where('id', $order['id'])->find();

        // 更新收货时间
        $order->ext = json_encode($order->setExt($order, ['confirm_time' => time()]));      // 收货时间
        $order->save();

        // 添加自动好评队列
        $config = Config::where('name', 'order')->cache(300)->find();        // 读取配置自动缓存 5 分钟
        $config = isset($config) ? json_decode($config['value'], true) : [];
        $close_days = (isset($config['order_auto_comment']) && $config['order_auto_comment'] > 0)
            ? $config['order_auto_comment'] : 7;       // 单位天 

        \think\Queue::later(($close_days * 86400), '\addons\shopro\job\OrderAutoOper@autoComment', $params, 'shopro');

        // 判断订单是否全部确认收货
        $noConfirm = OrderItem::where('order_id', $order['id'])->where('dispatch_status', '<>', OrderItem::DISPATCH_STATUS_GETED)->count();
        // 订单已全部确认收货
        if ($noConfirm <= 0) {
            //  购买奖励积分
            $score = $this->scoreSalesTotal($order->id);
            if( $score['score_sales']  > 0 ){
                \addons\shopro\model\User::score($score['score_sales'], $order->user_id, 'consume_get_score', $order->id);
            }
            //代理奖励积分
            if( $score['score_agent'] > 0 && $agent_user_id = $this->scoreAgent($order)){
                \addons\shopro\model\User::score($score['score_agent'], $agent_user_id, 'award_agency', $order->id);
            }
            // 触发订单完成钩子，可以在这里处理分销佣金等
            $data = ['order' => $order];
            \think\Hook::listen('order_confirm_finish', $data);

        }

        return $order;
    }
    /**
     * 计算购买商品奖励积分
     */
    public function scoreSalesTotal($order_id){
        $items = OrderItem::where('order_id', $order_id)->select();
        $score_sales = $score_agent = 0;
        foreach ($items as $key=>$value){
            $good_info =  \addons\shopro\model\Goods::where('id',$value['goods_id'])->find();
            $score_sales = isset($good_info) ? $score_sales + $good_info['score_sales']*$value['goods_num'] : 0;
            $score_agent = isset($good_info) ? $score_agent + $good_info['score_agent']*$value['goods_num'] : 0;
        }
        return ['score_sales'=>$score_sales,'score_agent'=>$score_agent];
    }
    /**
     * 计算代理商品奖励积分
     */
    public function scoreAgent($order){
        $agent = new \app\admin\model\shopro\commission\Agent;
        $agent_data = $agent->field('user_id,area_id')
            ->where('area_id ='.$order->area_id.' or area_id='.$order->city_id)
            ->where('level','in',[5,6])
            ->order('level','asc')
            ->select();
        if( !empty($agent_data)){
            foreach ($agent_data as $key=>$value){
                if($value->area_id == $order->area_id || $value->area_id == $order->city_id){
                    return  $value->user_id;
                }
            }
        }
        return false;
    }
}
